import { Anchor } from 'antd'
import { useEffect, useState } from 'react'

export default function PostAnchor() {
  const [anchors, setAnchors] = useState([])

  const updateToc = () => {
    setTimeout(() => {
      const article = document.querySelector('.markdown-body')
      if (article === null || article.hasAttribute('querySelectorAll')) return

      const hs = article.querySelectorAll('h1,h2,h3,h4')
      const anchor: any = []

      hs.forEach((item, idx) => {
        const h = item.nodeName.substring(0, 2).toLowerCase()
        item.id = `Anchor-${h}-${idx}`
        anchor.push({ id: `Anchor-${h}-${idx}`, text: item.textContent })
      })

      setAnchors(anchor)
    }, 100)
  }

  useEffect(() => {
    updateToc()
  }, [])

  return (
    <>
      <Anchor
        offsetTop={1}
        affix={false}
        showInkInFixed
      >
        {anchors.map((anchor: any, idx: number) => {
          switch (anchor.id[8]) {
            case '1': return <Anchor.Link key={idx} href={`#${anchor.id}`} title={<span style={{ paddingLeft: 0 }}>{anchor.text}</span>} />
            case '2': return <Anchor.Link key={idx} href={`#${anchor.id}`} title={<span style={{ paddingLeft: 16 }}>{anchor.text}</span>} />
            case '3': return <Anchor.Link key={idx} href={`#${anchor.id}`} title={<span style={{ paddingLeft: 32 }}>{anchor.text}</span>} />
            default: return <></>
          }
        })}
      </Anchor>
    </>
  )
}
